﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

using MINERP.MODEL.StartOrder;
using MINERP.MODEL.FoundationModel;
using MINERP.DAL;
using MINERP.DAL.StartOrder;
using MINERP.COM;
using MINERP.BLL.Common;
using System.Transactions;
using System.Data;
using MINERP.BLL.CustomerManage;
using ServiceInterfaces.DataContracts;
using System.ComponentModel;
using System.Threading;




namespace MINERP.BLL.StartOrder
{
    public class OrderBLL
    {
        private List<WorkOrderFlowListInfo> _workFlowListInfo = new List<WorkOrderFlowListInfo>();
        private  WorkFlowListBLL workFlowListBll = new WorkFlowListBLL();
        private StartOrderDAL _dal = new StartOrderDAL();


        public List<WorkOrderFlowListInfo> WorkFlowListInfo
        {
            get
            {
                if(_workFlowListInfo.Count<1)
                    _workFlowListInfo= GetAllWorkFlowListInfo();
                return _workFlowListInfo;
            }
        }
 
          /// <summary>
        /// 根据客户文件夹路径取得该客户的产品列表
          /// </summary>
          /// <param name="path">客户文件夹路径</param>
          /// <param name="orderInfoList">待开单产品列表</param>
          /// <param name="unit">单位</param>
          /// <param name="paperTypeInfo">当前纸型</param>
          /// <param name="PaperFaceInfo">当前纸面</param>
          /// <returns>true 有产品或照片已在待开单列表中，false 没有产品或者照片在待开单列表中</returns>
        public bool GetOrderInfoByCtmFolderPath(string path, List<OrderInfo> orderInfoList,string unit,PaperType_Info paperTypeInfo,PaperFace_Info PaperFaceInfo,string computerName,bool orderByCtmFolder)
        {
            bool flag = false;
            List<PhotoInfo> photolist = new List<PhotoInfo>();//已经存在的照片列表
            bool isfilePath = false;
            CreateTempOrderFolder(path);//创建开单移动照片临时文件夹
            PictrueBLL picbll = new PictrueBLL();

            DirectoryInfo destDi = new DirectoryInfo(path);
            foreach (var item in orderInfoList)
	        {
                photolist.AddRange(item.Photos);
	        }
           
           
            //检查待开单区有没有重复路径的照片
            if (destDi.Exists)
            {
                foreach (var item in destDi.GetFiles("*.*", SearchOption.AllDirectories))
                {
                    if (photolist.Exists(p => p.OldPicPath == item.FullName))
                        return true;
                }
            }
            else
            {
                
                if (photolist.Exists(p => p.OldPicPath == path))
                {
                    return true;
                }
            }


            int dirNum = 0;
            int photoNum1 =0;
            int photoNum2 = 0;
            int photoNum3 = 0;
            int photoNum4 = 0;
            int photoNum = 0;
            if (destDi.Exists)
            {
                dirNum = destDi.GetDirectories().Length;
                photoNum1 = destDi.GetFiles("*.jpg").Length;
                photoNum2 = destDi.GetFiles("*.jpeg").Length;
                photoNum3 = destDi.GetFiles("*.tif").Length;
                photoNum4 = destDi.GetFiles("*.tiff").Length;
                photoNum = photoNum1 + photoNum2 + photoNum3 + photoNum4;
            }
            else
            {
                if (File.Exists(path))
                {
                    dirNum = 0;
                    photoNum = 1;
                    isfilePath = true;
                  
                }
            }
            if (orderByCtmFolder) ////按拖动文件夹名为客人名字开单
            {
                if (isfilePath)
                {
                    throw new Exception("以客人目录开单方式不支持单拖拽文件！");
                }
                //#region客人名字开单
                if (dirNum > 0) //根目录下有文件夹
                {
                    if (photoNum > 0) //根目录下有照片和文件夹
                    {
                        throw new Exception("客户文件夹下还有照片没在产品文件夹中！");
                    }
                    else
                    {
                        //1带文件夹的产品
                        foreach (DirectoryInfo item in destDi.GetDirectories())
                        {
                            int file1 = item.GetFiles("*.jpg", SearchOption.AllDirectories).Length;
                            int file2 = item.GetFiles("*.jpeg", SearchOption.AllDirectories).Length;
                            int file3 = item.GetFiles("*.tif", SearchOption.AllDirectories).Length;
                            int file4 = item.GetFiles("*.tiff", SearchOption.AllDirectories).Length;
                            int picFile = file1 + file2 + file3 + file4;
                            if (picFile > 0) //产品文件夹有照片
                            {
                                OrderInfo oi = new OrderInfo();
                                oi.Remark = GetRemarkOfProduct(item.FullName);
                                oi.Unit = unit;
                                oi.CtmName = destDi.Name;
                                oi.OrderProductName = item.Name;
                                oi.PaperFaceName = PaperFaceInfo.Name;
                                oi.PapeTypeName = paperTypeInfo.Name;
                                ;
                                oi.OrilOrderPath = item.FullName;


                                string allPath = item.FullName;
                                int index4 = allPath.IndexOf(destDi.Name);
                                DirectoryInfo oldpath = new DirectoryInfo(item.FullName);
                                string productFolder = item.FullName.Replace(destDi.FullName, "").Trim('\\');
                                //oi.OrderPath = oldpath.Root.ToString() + "wh_order\\" + allPath.Substring(index4);
                                oi.OrderPath = oldpath.Root.ToString() + "wh_order\\" + productFolder;

                                oi.ProductNum = 1;
                                oi.IsFinishedGoods = false; //不是成品（不含照片产品）
                                oi.ComputerName = computerName;
                                if (_workFlowListInfo.Count < 1)
                                    _workFlowListInfo = GetAllWorkFlowListInfo(); //获取车间完整生产工艺
                                oi.workFlows = new List<WorkOrderFlowListInfo>();
                                foreach (var workflow in _workFlowListInfo)
                                {
                                    oi.workFlows.Add(new WorkOrderFlowListInfo()
                                        {
                                            AssignTime = DateTime.Now,
                                            IsEdit = false,
                                            CompletedTime = DateTime.Now,
                                            IsNecessery = false,
                                            ReceiveTime = DateTime.Now,
                                            Status = (int) OrderFlowListStatus.Wait,
                                            TechId = workflow.TechId,
                                            TechName = workflow.TechName,
                                            UserId = 0,
                                            OrderProductId = 0,
                                            WorkFlowListId = 0,
                                            WorkOrder = workflow.WorkOrder,
                                            IsUsefull = false,
                                            UserName = string.Empty,
                                            TechTime = workflow.TechTime,
                                            Techtype = workflow.Techtype,
                                            IsDesign = workflow.IsDesign
                                        }
                                    );
                                }
                                //oi.workFlows = GetAllWorkFlowListInfo();
                                GetPhotoInfoByOrderInfoFolder(item, oi, unit, paperTypeInfo, PaperFaceInfo);
                                orderInfoList.Add(oi);
                            }

                        }
                    }
                }
                else //以客人层开单并且根目录下没有文件夹
                {
                    if (photoNum > 0) //根目录下有照片
                    {

                        //2不带文件夹的产品
                        List<PhotoInfo> photoList = new List<PhotoInfo>();

                        List<FileInfo> fileInfoList = new List<FileInfo>();
                        if (destDi.Exists)
                        {
                            fileInfoList = destDi.GetFiles().ToList();
                        }
                        else
                        {
                            if (File.Exists(destDi.FullName))
                            {
                                fileInfoList.Add(new FileInfo(destDi.FullName));
                            }
                        }
                        foreach (FileInfo item in fileInfoList)
                        {
                            if (item.Extension.ToUpper() == ".JPG" || item.Extension.ToUpper() == ".JPEG" ||
                                item.Extension.ToUpper() == ".TIF" || item.Extension.ToUpper() == ".TIFF")
                            {


                                PhotoInfo photo = picbll.AddSinglePhotoNoDesign(item.FullName);

                                string allPath = item.FullName;
                                int index4 = allPath.IndexOf(destDi.Name, StringComparison.CurrentCulture);
                                DirectoryInfo oldpath = new DirectoryInfo(item.FullName);
                                if (isfilePath)
                                {
                                    string dirPath = Path.GetDirectoryName(item.FullName);
                                    string directName = dirPath.Substring(dirPath.LastIndexOf("\\") + 1);
                                    string fileName = Path.GetFileName(item.FullName);
                                    photo.PicPath = oldpath.Root.ToString() + "wh_order\\" + directName + "\\" +
                                                    allPath.Substring(allPath.LastIndexOf("\\") + 1);
                                    photo.Remark = fileName;
                                }
                                else
                                {
                                    //photo.PicPath = oldpath.Root.ToString() + "wh_order\\" + di.Name + "\\" + di.Name +
                                    //                allPath.Substring(allPath.LastIndexOf("\\") + 1);
                                    //photo.Remark = di.Name + "\\" +
                                                   //item.FullName.Substring(item.FullName.IndexOf(di.Name));

                                    string temp = item.FullName.Replace(destDi.FullName, "");
                                    //photo.PicPath = oldpath.Root.ToString() + "wh_order\\" + di.Name + "\\" + di.Name +
                                    //                allPath.Substring(allPath.LastIndexOf("\\") + 1);
                                    photo.PicPath = oldpath.Root.ToString() + "wh_order\\" + destDi.Name + "" + temp;
                                    //string temp = item.FullName.Replace(di.FullName,"");
                                    photo.Remark = temp;
                                }

                                photo.OldPicPath = item.FullName;
                                photo.isPictrue = true;

                                photo.PaperTypeName = paperTypeInfo.Name;
                                photo.PaperTypeID = paperTypeInfo.PaperTypeID;
                                photo.PaperFaceName = PaperFaceInfo.Name;
                                photo.PaperFaceId = PaperFaceInfo.PaperFaceID;

                                photoList.Add(photo);
                            }
                        }

                        OrderInfo oi = new OrderInfo();
                        oi.Remark = GetRemarkOfProduct(destDi.FullName);
                        oi.Unit = unit;
                        DirectoryInfo dirtempPath = new DirectoryInfo(destDi.FullName);
                        if (isfilePath)
                        {
                            string dirPath = destDi.Parent.Name;
                            //string directName = dirPath.Substring(dirPath.LastIndexOf("\\"));
                            oi.CtmName = dirPath;
                            oi.OrderProductName = Path.GetFileNameWithoutExtension(destDi.Name);
                            oi.OrilOrderPath = Directory.GetParent(destDi.FullName).FullName;
                            oi.OrderPath = dirtempPath.Root.ToString() + "wh_order\\" + oi.CtmName;
                        }
                        else
                        {
                            oi.CtmName = destDi.Name;
                            oi.OrderProductName = destDi.Name;
                            oi.OrilOrderPath = destDi.FullName;
                            oi.OrderPath = dirtempPath.Root.ToString() + "wh_order\\" + oi.CtmName + "\\" +
                                           oi.OrderProductName;
                        }
                        oi.Photos = photoList;

                        string tempath = destDi.FullName;
                        //int index = allPath.IndexOf(di.Name);



                        oi.PaperFaceName = PaperFaceInfo.Name;
                        oi.PapeTypeName = paperTypeInfo.Name;
                        oi.PageNum = 1;
                        oi.ProductNum = 1;
                        oi.IsFinishedGoods = false; //不是成品（不含照片产品）
                        oi.ComputerName = computerName;
                        if (_workFlowListInfo.Count < 1)
                            _workFlowListInfo = GetAllWorkFlowListInfo(); //获取车间完整生产工艺
                        oi.workFlows = new List<WorkOrderFlowListInfo>();
                        foreach (var workflow in _workFlowListInfo)
                        {
                            oi.workFlows.Add(new WorkOrderFlowListInfo()
                                {
                                    AssignTime = DateTime.Now,
                                    IsEdit = false,
                                    CompletedTime = DateTime.Now,
                                    IsNecessery = false,
                                    ReceiveTime = DateTime.Now,
                                    Status = (int) OrderFlowListStatus.Wait,
                                    TechId = workflow.TechId,
                                    TechName = workflow.TechName,
                                    UserId = 0,
                                    OrderProductId = 0,
                                    WorkFlowListId = 0,
                                    WorkOrder = workflow.WorkOrder,
                                    IsUsefull = false,
                                    UserName = string.Empty,
                                    TechTime = workflow.TechTime,
                                    Techtype = workflow.Techtype,
                                    IsDesign = workflow.IsDesign
                                }
                            );
                        }

                        orderInfoList.Add(oi);

                    }
                    else
                    {
                        throw new Exception("空文件夹！");
                    }

                }
//#endregion
            }
            else //按拖动文件夹名为产品名字开单
            {
                if (photoNum > 0||dirNum>0) //根目录下有照片
                {

                    //2不带文件夹的产品
                    List<PhotoInfo> photoList = new List<PhotoInfo>();

                    List<FileInfo> fileInfoList = new List<FileInfo>();
                    if (destDi.Exists)
                    {
                        fileInfoList = destDi.GetFiles("*.*", SearchOption.AllDirectories).ToList();
                    }
                    else
                    {
                        if (File.Exists(destDi.FullName))
                        {
                            fileInfoList.Add(new FileInfo(destDi.FullName));
                        }
                    }
                    if (fileInfoList.Count == 0)
                    {
                        throw  new Exception("空文件夹");
                    }
                    List<string> listFile = new List<string>();
                    foreach (FileInfo item in fileInfoList)
                    {
                        if (item.Extension.ToUpper() == ".JPG" || item.Extension.ToUpper() == ".JPEG" ||
                            item.Extension.ToUpper() == ".TIF" || item.Extension.ToUpper() == ".TIFF")
                        {
                            listFile.Add(item.FullName);
                        }
                    }
                    if (listFile.Count == 0)
                    {
                        throw new Exception("空文件夹");
                    }
                    //List<PhotoInfo> photoList = new List<PhotoInfo>();
                    //foreach (FileInfo item in fileInfoList)
                    foreach (string strPath in listFile)              
                    {
                        FileInfo photoitem = new FileInfo(strPath);
                        if (photoitem.Extension.ToUpper() == ".JPG" || photoitem.Extension.ToUpper() == ".JPEG" ||
                            photoitem.Extension.ToUpper() == ".TIF" || photoitem.Extension.ToUpper() == ".TIFF")
                        {

                            DirectoryInfo ProducDir = new DirectoryInfo(path);
                            string strOld;
                            try
                            {
                                strOld = ProducDir.Parent.Parent.FullName;
                            }
                            catch
                            {
                                throw new Exception("请拖开单文件夹下面的文件夹!");
                            }
                            PhotoInfo photo = picbll.AddSinglePhotoNoDesign(photoitem.FullName);

                            string allPath = photoitem.FullName;
                            int index4 = allPath.IndexOf(destDi.Name, StringComparison.CurrentCulture);
                            DirectoryInfo oldpath = new DirectoryInfo(photoitem.FullName);
                            //photo.PicPath = oldpath.Root.ToString() + "wh_order\\" + di.Name + "\\" + di.Name + allPath.Substring(allPath.LastIndexOf("\\"));
                            //photo.PicPath = allPath.Replace(strOld, oldpath.Root.ToString() + "wh_order\\");
                            ////photo.PicPath = oldpath.Root.ToString() + "wh_order\\" +di.Parent+"\\"+ allPath.Substring(allPath.LastIndexOf(di.Name));
                            photo.OldPicPath = photoitem.FullName;
                            photo.isPictrue = true;
                            //photo.Remark = di.Name + "\\" + item.FullName.Substring(item.FullName.IndexOf(di.Name));
                            //string strR1 = item.FullName.Substring(item.FullName.IndexOf(di.Name));
                            if (isfilePath)
                            {
                                string dirPath = Path.GetDirectoryName(photoitem.FullName);
                                string filefullName = Path.GetFileName(strPath);
                               // string directName = dirPath.Substring(dirPath.LastIndexOf("\\") + 1);
                                string fileName = Path.GetFileNameWithoutExtension(photoitem.FullName);
                                photo.PicPath = oldpath.Root.ToString() + "wh_order\\" + destDi.Parent.Name +"\\"+ fileName + "\\" +
                                               filefullName;
                                photo.Remark = filefullName;
                            }
                            else
                            {
                                string temp = photoitem.FullName.Replace(destDi.FullName, "");
                                //photo.PicPath = oldpath.Root.ToString() + "wh_order\\" + di.Name + "\\" + di.Name +
                                //                allPath.Substring(allPath.LastIndexOf("\\") + 1);
                                if (destDi.Parent == null)
                                {
                                    photo.PicPath = oldpath.Root.ToString() + "wh_order\\" +
                                                                                       destDi.Name + "" + temp;
                                }
                                else
                                {
                                    photo.PicPath = oldpath.Root.ToString() + "wh_order\\" + destDi.Parent.Name + "\\" +
                                                    destDi.Name + "" + temp;
                                }
                                //string temp = item.FullName.Replace(di.FullName,"");
                                photo.Remark = temp;
                            }
                            //photo.Remark = strR1.Substring(strR1.IndexOf("\\") + 1); ;
                            photo.PaperTypeName = paperTypeInfo.Name;
                            photo.PaperTypeID = paperTypeInfo.PaperTypeID;
                            photo.PaperFaceName = PaperFaceInfo.Name;
                            photo.PaperFaceId = PaperFaceInfo.PaperFaceID;

                            photoList.Add(photo);
                        }
                    }

                    OrderInfo oi = new OrderInfo();
                    oi.Remark = GetRemarkOfProduct(destDi.FullName);
                    oi.Unit = unit;
                    oi.CtmName = destDi.Parent.Name;
                    oi.OrderProductName = destDi.Name;
                    oi.Photos = photoList;
                    oi.OrilOrderPath = destDi.FullName;
                    string tempath = destDi.FullName;
                    //int index = allPath.IndexOf(di.Name);
                    //DirectoryInfo dirtempPath = new DirectoryInfo(di.FullName);
                    //oi.OrderPath = dirtempPath.Root.ToString() + "wh_order\\" +di.Parent +"\\"+ di.Name;
                    DirectoryInfo dirtempPath = new DirectoryInfo(destDi.FullName);
                    if (isfilePath)
                    {
                        string ctmPath = destDi.Parent.Name;
                        //string directName = dirPath.Substring(dirPath.LastIndexOf("\\"));
                        oi.CtmName = ctmPath;
                        oi.OrderProductName = Path.GetFileNameWithoutExtension(destDi.Name);
                        oi.OrilOrderPath = Directory.GetParent(destDi.FullName).FullName;
                        oi.OrderPath = dirtempPath.Root.ToString() + "wh_order\\" + oi.OrderProductName;
                    }
                    else
                    {
                        //oi.CtmName = di.Name;
                        //oi.OrderProductName = di.Name;
                        oi.OrilOrderPath = destDi.FullName;
                        oi.OrderPath = dirtempPath.Root.ToString() + "wh_order\\" + oi.CtmName + "\\" +
                                       oi.OrderProductName;
                    }
                    oi.PaperFaceName = PaperFaceInfo.Name;
                    oi.PapeTypeName = paperTypeInfo.Name;
                    oi.PageNum = 1;
                    oi.ProductNum = 1;
                    oi.IsFinishedGoods = false; //不是成品（不含照片产品）
                    oi.ComputerName = computerName;
                    if (_workFlowListInfo.Count < 1)
                        _workFlowListInfo = GetAllWorkFlowListInfo(); //获取车间完整生产工艺
                    oi.workFlows = new List<WorkOrderFlowListInfo>();
                    foreach (var workflow in _workFlowListInfo)
                    {
                        oi.workFlows.Add(new WorkOrderFlowListInfo()
                            {
                                AssignTime = DateTime.Now,
                                IsEdit = false,
                                CompletedTime = DateTime.Now,
                                IsNecessery = false,
                                ReceiveTime = DateTime.Now,
                                Status = (int) OrderFlowListStatus.Wait,
                                TechId = workflow.TechId,
                                TechName = workflow.TechName,
                                UserId = 0,
                                OrderProductId = 0,
                                WorkFlowListId = 0,
                                WorkOrder = workflow.WorkOrder,
                                IsUsefull = false,
                                UserName = string.Empty,
                                TechTime = workflow.TechTime,
                                Techtype = workflow.Techtype,
                                IsDesign = workflow.IsDesign


                            }
                        );
                    }

                    orderInfoList.Add(oi);
                }
                else
                {
                    throw new Exception("空文件夹！");
                }
            }

            return flag; 
        }

        /// <summary>
        /// 根据产品文件夹取得所有产品所有照片
        /// </summary>
        /// <param name="inProductdir">产品文件夹</param>
        /// <returns></returns>
        public void GetPhotoInfoByOrderInfoFolder(DirectoryInfo inProductdir,OrderInfo oi,string unit,PaperType_Info paperTypeInfo,PaperFace_Info paperFaceInfo)
        {
            PictrueBLL picturebll = new PictrueBLL();
            int photoNum = 0;
            List<PhotoInfo> listphoto = new List<PhotoInfo>();
            foreach (FileInfo photoitem in inProductdir.GetFiles("*.*",SearchOption.AllDirectories))
            {//一张一张的照片
                PhotoInfo photo = new PhotoInfo();
      
                if (photoitem.Extension.ToUpper() == ".JPG" || photoitem.Extension.ToUpper() == ".JPEG" || photoitem.Extension.ToUpper() == ".TIF" || photoitem.Extension.ToUpper() == ".TIFF")
                {
                    photo= picturebll.AddSinglePhotoNoDesign(photoitem.FullName);
                    photo.isPictrue = true;
                    photoNum++;
                    photo.PaperFaceId = paperFaceInfo.PaperFaceID;
                    photo.PaperFaceName = paperFaceInfo.Name;
                    photo.PaperTypeID = paperTypeInfo.PaperTypeID;
                    photo.PaperTypeName = paperTypeInfo.Name;
                    photo.Unit = unit;
                    //string strR1=photoitem.FullName.Substring(photoitem.FullName.IndexOf(oi.CtmName));
                    //string str2=strR1.Substring(strR1.IndexOf("\\")+1);
                    //photo.Remark = str2.Substring(str2.IndexOf("\\") + 1); ;
                    string remark = photoitem.FullName.Replace(inProductdir.FullName, "").Trim();
                    photo.Remark = remark;
                }
                else
                {
                    photo.isPictrue = false;
                }
                string allPath = photoitem.FullName;
                int index4 = allPath.IndexOf(oi.CtmName);

                DirectoryInfo oldpath = new DirectoryInfo(photoitem.FullName);

                //photo.PicPath = oldpath.Root.ToString() + "wh_order\\" + allPath.Substring(index4);
                photo.PicPath = Path.Combine(oi.OrderPath, photo.Remark);
                photo.OldPicPath = photoitem.FullName;
                listphoto.Add(photo);
            }
            oi.PageNum = photoNum;//产品照片数量
            oi.Photos = listphoto;//产品照片列表
        }

        /// <summary>
        /// 获取照片的临时文件夹
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public string GetPhotoTempPath(string path,string ctmFolderName)
        {
            return "";
        }

        /// <summary>
        /// 获得所有有效商户
        /// </summary>
        /// <returns></returns>
        public List<ShopInfo_Order> GetShopList()
        {
            List<ShopInfo_Order> listShop = new List<ShopInfo_Order>();
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                foreach (var item in db.Shop.Where(s=>s.Status==1).ToList())//"1"表示有效的商户
                {
                    ShopInfo_Order shop = new ShopInfo_Order()
                    {
                        ShopId = item.ShopId,
                        ShopName = item.shopName,
                        MnemonicCode = item.mnemonicCode,
                        PaperFaceId = item.PaperFaceId == null ? 0 : (int)item.PaperFaceId,
                        PaperTypeId = item.PaperTypeId == null ? 0 : (int)item.PaperTypeId,
                        Priority = item.Priority == null ? 0 :(int) item.Priority
                    };
                    listShop.Add(shop);
                }
            }
            return listShop;
        }

        /// <summary>
        /// 获得打印机列表
        /// </summary>
        /// <returns></returns>
        public List<ServiceInterfaces.DataContracts.Printer_Info> GetPrinterList()
        {
            List<ServiceInterfaces.DataContracts.Printer_Info> listPrinterInfo = new List<ServiceInterfaces.DataContracts.Printer_Info>();
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                foreach (var item in db.printer.ToList())
                {
                    ServiceInterfaces.DataContracts.Printer_Info printerInfo = new ServiceInterfaces.DataContracts.Printer_Info()
                    {
                        PName = item.PName,
                        PrinterID = item.PrinterID,
                        PDPI = item.PDPI

                    };
                    listPrinterInfo.Add(printerInfo);
                }
            }
            return listPrinterInfo;
        }

        /// <summary>
        /// 获取全部有效员工
        /// </summary>
        /// <returns></returns>
        public List<User_Info> GetUserInfoList()
        {
            List<User_Info> list = new List<User_Info>();
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                foreach (var item in db.users.Where(u=>u.IsUseful ==true).ToList())
                {
                    User_Info userInfo = new User_Info()
                    {
                        UserID = item.userID,
                        UserName = item.UserName,
                        LoginName = item.LoginName,
                        IsOnline = item.IsOnline

                    };
                    list.Add(userInfo);
                }
            }
            return list;
        }

        /// <summary>
        /// 获得商户附加收费项目
        /// </summary>
        /// <param name="shopId"></param>
        /// <returns></returns>
        public List<CommonChargeItemInfo> GetCommonChargeItemInfoList(int shopId)
        {
            List<CommonChargeItemInfo> list = new List<CommonChargeItemInfo>();
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            { 
                List<Shop_CommonChargeItem_Price> templist =db.Shop_CommonChargeItem_Price.Where(c=>c.ShopId ==shopId).ToList();
                if (templist.Count > 0)
                {
                    foreach (var item in templist)
                    {
                        if (!item.CommonChargeItemReference.IsLoaded)
                            item.CommonChargeItemReference.Load();
                        CommonChargeItemInfo cInfo = new CommonChargeItemInfo()
                        {
                            CommonChargeItemId = item.CommonChargeItem.CommonChargeItemId,
                            IsUsefull = false,
                            ItemName = item.CommonChargeItem.ItemName
                        };
                        list.Add(cInfo);
                    }
                }

            }
            return list;
        }
        /// <summary>
        /// 获取商户所勾选的产品模版
        /// </summary>
        /// <param name="shopId"></param>
        /// <param name="unit"></param>
        /// <returns></returns>
        public List<ProductTempleteInfo> GetProductTempleteList(int shopId,string unit)
        {
            List<ProductTempleteInfo> listProductTemplete = new List<ProductTempleteInfo>();
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                List<Shop_Product_Price> sppList = db.Shop_Product_Price.Where(s => s.Shop.ShopId == shopId&&s.Tb_Product.Status ==1).ToList().OrderByDescending(s=>s.usedTimes).ToList();
                List<Shop_Tech_User> stuList = db.Shop_Tech_User.Where(s => s.ShopId == shopId).ToList();
                foreach (var item in sppList)
                {
                    ServiceInterfaces.DataContracts.Printer_Info printerInfo=null;
                    if(!item.ShopReference.IsLoaded)
                        item.ShopReference.Load();
                    if(!item.Tb_ProductReference.IsLoaded)
                        item.Tb_ProductReference.Load();
                    if (!item.Tb_Product.paperFaceReference.IsLoaded)
                        item.Tb_Product.paperFaceReference.Load();
                    if (!item.Tb_Product.paperTypeReference.IsLoaded)
                        item.Tb_Product.paperTypeReference.Load();
                    if(!item.Tb_Product.Tb_PorductCategoryReference.IsLoaded)
                        item.Tb_Product.Tb_PorductCategoryReference.Load();
                    if(!item.Tb_Product.Tb_OutShop_ProductCategory.IsLoaded)
                        item.Tb_Product.Tb_OutShop_ProductCategory.Load();
                    if(!item.Tb_Product.printerReference.IsLoaded)
                        item.Tb_Product.printerReference.Load();
                    if (!item.Tb_Product.Tb_FlowTemplate.IsLoaded)
                        item.Tb_Product.Tb_FlowTemplate.Load();
                    if(!item.Tb_Product.tb_ProductTypeReference.IsLoaded)
                        item.Tb_Product.tb_ProductTypeReference.Load();
                    printer printer = item.Tb_Product.printer;
                    if (printer != null)
                    {
                        printerInfo = new ServiceInterfaces.DataContracts.Printer_Info()
                        {
                            PrinterID = item.Tb_Product.printer.PrinterID,
                            PName = item.Tb_Product.printer.PName,
                            PDPI =item.Tb_Product.printer.PDPI
                        };
                    }

                    List<OutProcessShopInfo> OutProcessShopList = new List<OutProcessShopInfo>();//委外商列表
                    foreach (var outshop in item.Tb_Product.Tb_OutShop_ProductCategory)
                    {
                        if(!outshop.OutProcessShopReference.IsLoaded)
                            outshop.OutProcessShopReference.Load();
                        OutProcessShopInfo outshopInfo = new OutProcessShopInfo()
                        {
                            IsDefaultOurProcessShop = outshop.IsDefaultOutShop,//产品默认委外商
                            OutShopId = outshop.OutProcessShop.OutShopId,
                            OutShopName = outshop.OutProcessShop.OutShopName
                        };
                        OutProcessShopList.Add(outshopInfo);
                    }

                    List<WorkOrderFlowListInfo> workflowList = new List<WorkOrderFlowListInfo>();//产品流程

                    foreach (var workflow in item.Tb_Product.Tb_FlowTemplate)
                    {
                       
                        if(!workflow.tb_TechReference.IsLoaded)
                            workflow.tb_TechReference.Load();

                        WorkOrderFlowListInfo workflowInfo = new WorkOrderFlowListInfo()
                        {

                            AssignTime = DateTime.Now,
                            CompletedTime = DateTime.Now,
                            IsEdit = false,
                            ReceiveTime = DateTime.Now,
                            Status = (int)OrderFlowListStatus.Wait,
                            TechId = workflow.tb_Tech.TechId,
                            TechName = workflow.tb_Tech.TechName, 
                            UserId = 0,
                            WorkOrder = workflow.WorkOrder,
                            IsNecessery = workflow.IsNecessery,
                            Techtype = workflow.tb_Tech.TechType,
                            IsDesign = workflow.tb_Tech.IsDesign,
                            TechTime = workflow.tb_Tech.NeedTime
                        };

                        #region 商户节点指定操作员
                        Shop_Tech_User stu = stuList.FirstOrDefault(s =>s.TechId ==workflow.tb_Tech.TechId);
                        if (stu != null)
                        {
                            if (!stu.usersReference.IsLoaded)
                                stu.usersReference.Load();
                            workflowInfo.UserName = stu.users.UserName;
                        }
                        else
                        {
                            workflowInfo.UserName = string.Empty;
                        }

                        workflowList.Add(workflowInfo);
                        #endregion
                    }

                    #region 绑定的节点和附加收费
                    List<TechCommonChargeItemInfo> TechCommonChargeItemInfoList = new List<TechCommonChargeItemInfo>();//绑定好的节点与附加收费
                    List<tb_Tech> techList = db.tb_Tech.ToList();
                    foreach (var tech in techList)
                    {
                        if (!tech.CommonChargeItem.IsLoaded)
                            tech.CommonChargeItem.Load();
                        foreach (var techcomcharge in tech.CommonChargeItem)
                        {
                            TechCommonChargeItemInfo techComChargeInfo = new TechCommonChargeItemInfo()
                            {
                                TechId = tech.TechId,
                                TechName = tech.TechName,
                                CommonChargeItemId = techcomcharge.CommonChargeItemId,
                                CommonChargeItemName = techcomcharge.ItemName
                            };
                            TechCommonChargeItemInfoList.Add(techComChargeInfo);
                        }
                        
                    }
                    #endregion

                    #region 绑定的产品和附加收费
                    List<ProductCommonChargeItemInfo> productCommonChargeItemInfoList = new List<ProductCommonChargeItemInfo>();//绑定好的产品与附加收费
                    if (!item.Tb_Product.CommonChargeItem.IsLoaded)
                        item.Tb_Product.CommonChargeItem.Load();
                    foreach (var comChargeItem in item.Tb_Product.CommonChargeItem)
                    {
                        ProductCommonChargeItemInfo produtcomm = new ProductCommonChargeItemInfo()
                        {
                            CommonChargeItemId = comChargeItem.CommonChargeItemId,
                            CommonChargeItemName = comChargeItem.ItemName,
                            ProductId = item.Tb_Product.ProuctId
                        };
                        productCommonChargeItemInfoList.Add(produtcomm);
                    }
                    #endregion

                    ProductTempleteInfo p = new ProductTempleteInfo()
                    {
                        AppendPrice = item.AppendPrice,
                        Height = item.Tb_Product.Height,
                        PageNum = item.Tb_Product.PageNum,
                        ProductName = item.Tb_Product.ProductName,
                        ProuctId = item.ProductId,
                        UnitPrice = item.UnitPrice,
                        Width = item.Tb_Product.Width,
                        UsedTimes = item.usedTimes == null ? 0 : (int)item.usedTimes,
                        ProductCategoryName = item.Tb_Product.Tb_PorductCategory.ProductCategoryName,
                        ProductCategoryDes = item.Tb_Product.Tb_PorductCategory.ProductCategoryDes,
                        MnemonicCode = item.Tb_Product.mnemonicCode,
                        DefaultPrinter = printerInfo,
                        OutProcessShopList = OutProcessShopList,
                        WorkOrderFlowList = workflowList,
                        ProductTypeCode = item.Tb_Product.tb_ProductType.ProductTypeCode,
                        techCommonChargeItemInfoList = TechCommonChargeItemInfoList,
                        productCommonChargeItemInfoList = productCommonChargeItemInfoList,
                        ProductDes = item.Tb_Product.ProductDes,
                        PaperFaceID = item.Tb_Product.paperFace.PaperFaceID,
                        PaperFaceName =item.Tb_Product.paperFace.Name,
                        PaperTypeID = item.Tb_Product.paperType.PaperTypeID,
                        PaperTypeName =item.Tb_Product.paperType.Name,
                        CoverHeight = item.Tb_Product.CoverHeight,
                        CoverWidth = item.Tb_Product.CoverWidth
                          
                    };
                    switch (unit)
                    {
                        case "厘米":

                            p.ProductSize = string.Format("{0}x{1}cm", Math.Round((decimal)(item.Tb_Product.Width * 2.54), 2, MidpointRounding.AwayFromZero), Math.Round((decimal)(item.Tb_Product.Height * 2.54), 2, MidpointRounding.AwayFromZero));
                            break;
                        case "英寸":
                            p.ProductSize = string.Format("{0}x{1}inch", Math.Round((decimal)item.Tb_Product.Width, 2, MidpointRounding.AwayFromZero), Math.Round((decimal)item.Tb_Product.Height, 2, MidpointRounding.AwayFromZero));
                            break;                       
                        case "米":
                            p.ProductSize = string.Format("{0}x{1}m", Math.Round((decimal)(item.Tb_Product.Width * 2.54 / 100), 2, MidpointRounding.AwayFromZero), Math.Round((decimal)(item.Tb_Product.Height * 2.54 / 100), 2, MidpointRounding.AwayFromZero));
                            break;
                        default:
                            p.ProductSize = string.Format("{0}x{1}cm", Math.Round((decimal)(item.Tb_Product.Width * 2.54), 2, MidpointRounding.AwayFromZero), Math.Round((decimal)(item.Tb_Product.Height * 2.54), 2, MidpointRounding.AwayFromZero));
                            break;                    
                    }
                    listProductTemplete.Add(p);

                    Thread.Sleep(1);
                    
                }
            }
            return listProductTemplete.OrderByDescending(p=>p.UsedTimes).ToList();
        }

        /// <summary>
        /// 获取商户特有的产品集合
        /// </summary>
        /// <param name="shopId"></param>
        /// <returns></returns>
        public List<ProductTempleteInfo> GetShopProductList(int shopId,string unit)
        {
            try
            {
                List<ProductTempleteInfo> products = new List<ProductTempleteInfo>();
                int delStatus = (int)COM.ProductStatus.Delete;

                DataTable dt = _dal.GetProductShop(shopId);
                List<ProductTempleteInfo> orderProducts = products.OrderBy(p => p.Width).ToList();
                DataTable dtPC = _dal.GetProductCommonChange();
                List<ProductCommonChargeItemInfo> listpci = new List<ProductCommonChargeItemInfo>();
                foreach (DataRow dw in dtPC.Rows)
                {
                    ProductCommonChargeItemInfo pc = new ProductCommonChargeItemInfo();
                    pc.CommonChargeItemId = Convert.ToInt32(dw["CommonChargeItemId"]);
                    pc.ProductId = Convert.ToInt32(dw["Productid"]);
                    pc.CommonChargeItemName = Convert.ToString(dw["ItemName"]);
                    listpci.Add(pc);
                }
                foreach (DataRow r in dt.Rows)
                {
                    if (Convert.ToInt32(r["Status"]) == delStatus)
                        continue;
                    ProductTempleteInfo pd = new ProductTempleteInfo();
                    
                    pd.ProuctId = Convert.ToInt32(r["ProductID"]);
                    pd.ProductName = r["ProductName"].ToString();
                    pd.Width = Convert.ToSingle(r["Width"]);
                    pd.Height = Convert.ToSingle(r["Height"]);
                    pd.PageNum = Convert.ToInt32(r["PageNum"]);
                    pd.ProductCategoryID = Convert.ToInt32(r["ProductCategoryID"]);
                    pd.ProductCategoryName = r["ProductCategoryName"].ToString();
                    pd.ProductTypeCode = Convert.ToInt32(r["productTypeCode"]);      //产品类型  1需要设计的产品 2不需要设计的产品 3需要指定尺寸的扩印 4直接扩印 5不含照片产品
                    pd.PaperFaceID = Convert.ToInt32(r["PaperFaceID"]);
                    pd.PaperTypeID = Convert.ToInt32(r["PaperTypeID"]);
                    pd.PaperTypeName = r["PaperTypeName"].ToString();
                    pd.PaperFaceName = r["PaperFaceName"].ToString();
                    pd.MnemonicCode = r["ZJCode"].ToString();
                    if (r["UsedTimes"] != DBNull.Value)
                        pd.UsedTimes = Convert.ToInt32(r["UsedTimes"]);

                    pd.productCommonChargeItemInfoList = listpci.Where(pc => pc.ProductId == pd.ProuctId).ToList();

                    switch (unit)
                    {
                        case "厘米":

                            pd.ProductSize = string.Format("{0}x{1}cm", Math.Round((decimal)(pd.Width * 2.54), 2, MidpointRounding.AwayFromZero), Math.Round((decimal)(pd.Height * 2.54), 2, MidpointRounding.AwayFromZero));
                            break;
                        case "英寸":
                            pd.ProductSize = string.Format("{0}x{1}inch", Math.Round((decimal)pd.Width, 2, MidpointRounding.AwayFromZero), Math.Round((decimal)pd.Height, 2, MidpointRounding.AwayFromZero));
                            break;
                        case "米":
                            pd.ProductSize = string.Format("{0}x{1}m", Math.Round((decimal)(pd.Width * 2.54 / 100), 2, MidpointRounding.AwayFromZero), Math.Round((decimal)(pd.Height * 2.54 / 100), 2, MidpointRounding.AwayFromZero));
                            break;
                        default:
                            pd.ProductSize = string.Format("{0}x{1}cm", Math.Round((decimal)(pd.Width * 2.54), 2, MidpointRounding.AwayFromZero), Math.Round((decimal)(pd.Height * 2.54), 2, MidpointRounding.AwayFromZero));
                            break;
                    }

                    products.Add(pd);
                }
                return products;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        /// <summary>
        /// 获得全部商户以及对应所勾选的产品模版
        /// </summary>
        /// <param name="unit"></param>
        /// <returns></returns>
        public Dictionary<int, List<ProductTempleteInfo>> GetAllShopProductTempleteList(string unit)
        {
            Dictionary<int, List<ProductTempleteInfo>> dic = new Dictionary<int, List<ProductTempleteInfo>>();
            List<Shop> shopList = null;
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                shopList = db.Shop.Where(s=>s.Status ==1).ToList();
            }

            foreach (var shop in shopList)
            {
                dic.Add(shop.ShopId, GetProductTempleteList(shop.ShopId, unit));
                //dic.Add(shop.ShopId, GetShopProductList(shop.ShopId, unit));
            }
            return dic;

        }

        /// <summary>
        /// 获取商户已勾选的纸型列表
        /// </summary>
        /// <param name="shopId"></param>
        /// <returns></returns>
        public List<PaperType_Info> GetShopPaperTypeInfoList(int shopId)
        {
            List<PaperType_Info> list = new List<PaperType_Info>();

            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                Shop shop = db.Shop.First(s=>s.ShopId  ==shopId);
                if (!shop.Shop_Paper_Price.IsLoaded)
                {
                    shop.Shop_Paper_Price.Load();
                }
                foreach (var item in shop.Shop_Paper_Price)
                {
                    if (!item.paperTypeReference.IsLoaded)
                    {
                        item.paperTypeReference.Load();
                    }
                    PaperType_Info pt = new PaperType_Info()
                    {
                        Name = item.paperType.Name,
                        PaperTypeID = item.paperType.PaperTypeID,
                        Remark =item.paperType.remark
                    };
                    list.Add(pt);
                }
            }
            return list;
        }

        /// <summary>
        /// 获得所有有效纸面
        /// </summary>
        /// <returns></returns>
        public List<PaperFace_Info> GetPaperFaceInfoList()
        {
            List<PaperFace_Info> list = new List<PaperFace_Info>();
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                foreach (var item in db.paperFace.Where(p=>p.Status ==1).ToList())
                {
                    PaperFace_Info pf = new PaperFace_Info()
                    {
                        Name = item.Name,
                        PaperFaceID = item.PaperFaceID,
                        Remark = item.remark
                    };
                    list.Add(pf);
                }
            }
            return list;
        }

        /// <summary>
        /// 获取完整的流程
        /// </summary>
        /// <returns></returns>
        private List<WorkOrderFlowListInfo> GetAllWorkFlowListInfo()
        {
            List<WorkOrderFlowListInfo> workflowlist = new List<WorkOrderFlowListInfo>();
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                List<tb_Tech> techList = db.tb_Tech.OrderBy(t=>t.WokerOrder).ToList();
                foreach (var item in techList)
                {
                    WorkOrderFlowListInfo workflow = new WorkOrderFlowListInfo()
                    {
                        AssignTime = DateTime.Now,
                        IsEdit = false,
                        CompletedTime = DateTime.Now,
                        IsNecessery = false,
                        ReceiveTime = DateTime.Now,
                        Status = (int)OrderFlowListStatus.Wait,
                        TechId = item.TechId,
                        TechName = item.TechName,
                        UserId = 0,
                        OrderProductId = 0,
                        WorkFlowListId = 0,
                        WorkOrder = item.WokerOrder,
                        IsUsefull = false,
                        UserName = string.Empty,
                        Techtype = item.TechType,
                        IsDesign = item.IsDesign,
                        TechTime = item.NeedTime
                         
                    };

                    workflowlist.Add(workflow);
                }
            }

            return workflowlist;
        }

        /// <summary>
        /// 创建开单移动照片临时文件夹
        /// </summary>
        /// <param name="path"></param>
        private void CreateTempOrderFolder(string path)
        {
            DirectoryInfo dir = new DirectoryInfo(path);
           
            if (!Directory.Exists(dir.Root.FullName + "\\wh_order"))
            {
                Directory.CreateDirectory(dir.Root.FullName + "\\wh_order");
            }
        }

        /// <summary>
        /// 插入占位用的订单包,并返回订单包号
        /// </summary>
        public string AddOrderBagTemp(out int orderID, out string bagCode, int userID)
        {
            try
            {
                using (newSampleYPDBEntities db = new newSampleYPDBEntities())
                {
                    Tb_OrderBag orderBag = new Tb_OrderBag();
                    orderBag.BagCode = "1000000000";
                    orderBag.BagName = "xxx";
                    orderBag.Shop = db.Shop.First();
                    orderBag.OrderTime = DateTime.Now;
                    orderBag.CompleteTime = DateTime.Now;
                    orderBag.FetchTime = DateTime.Now;
                    orderBag.Status = 100;
                    orderBag.Priority = 4;
                    orderBag.EditUserID = 0;
                    orderBag.Type = (int)COM.OrderBagType.normal;
                    orderBag.users = db.users.First(u=>u.userID ==userID);
                    db.SaveChanges();

                    string bagID = orderBag.EntityKey.EntityKeyValues[0].Value.ToString();
                    orderID = Convert.ToInt32(bagID);
                    bagCode = "1" + string.Format("{0:d9}", orderID);
                }
                return bagCode;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 开单
        /// </summary>
        public void AddOrderBag(object sender, DoWorkEventArgs e,List<OrderInfo> orderInfolist, int OrderID, string OrderBagCode, string orderName, int orderPriority, int shopID, string shopName, DateTime orderTime, DateTime preCompleteTime, string orderRemark, int userId)
        {
            List<WorkOrderFlowList> startOrderFlows = new List<WorkOrderFlowList>();       //开单流程，插入开单信息后统计开单员业绩
            //List<string> PhotoTemps = new List<string>();       //开单断网后照片复位
            //List<string> MovedTarPaths = new List<string>();    //上次断网时已移动了的照片路径
            List<orderInfo> addProductInfo = new List<orderInfo>();     //新插入的产品集合
            List<photoInfo> addPhotoInfo = new List<photoInfo>();       //新插入的照片集合 
            DateTime realOrderTime = _dal.GetServerTime();                //真实开单时间取服务器的时间
            preCompleteTime = realOrderTime.Add(preCompleteTime - orderTime);   //真实预计完成时间=真实开单时间+(本地预计完成时间-本地开单时间)
            orderTime = realOrderTime;
            System.Transactions.TransactionOptions options = new TransactionOptions();
            options.Timeout = new TimeSpan(0, 0, 600);
            options.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;
            Tb_OrderBag tb_order = null;
            int connectTime = 0;
            //double orderAreas = 0;
            try
            {
                using (newSampleYPDBEntities db = new newSampleYPDBEntities())
                {
                    if (db.Connection.State != System.Data.ConnectionState.Open)
                    {
                        db.Connection.Open();
                    }

                    using (System.Data.Common.DbTransaction tran = db.Connection.BeginTransaction(System.Data.IsolationLevel.ReadCommitted))
                    {
                        Shop shop = db.Shop.First(s => s.ShopId == shopID);
                        shop.LastPrintDate = DateTime.Now;
                        db.SaveChanges();
                        List<string> productPaths = new List<string>();             //保存产品的路径,出错后删除复制的产品信息

                        string SaveTotalPath = db.FileDirPath.First(f => f.Des == "已开单").FileDir;                 //照片在服务器上的总路径

                        //string DelPath = SaveTotalPath + "\\" + shopName + "\\" + DateTime.Now.Date.ToString("yyyy-MM-dd") + "\\" + OrderID.ToString() + "_" + orderName;    //如果出错删除该目录
                        string DelPath = SaveTotalPath + "\\" + shopName + "\\" + DateTime.Now.Date.ToString("yyyy-MM-dd") + "\\" + OrderID.ToString();    //如果出错删除该目录
                        try
                        {
                            //1 保存订单包

                            tb_order = db.Tb_OrderBag.Where("it.OrderBagId=" + OrderID).FirstOrDefault();
                            if (tb_order == null)
                            {
                                throw new Exception("同一帐号在别处正打开，请退出其它处登陆，重新打开开单界面，再进行开单！");
                            }
                            tb_order.BagCode = OrderBagCode;
                            tb_order.BagName = orderName;
                            tb_order.Priority = orderPriority;
                            tb_order.Shop = db.Shop.First(s => s.ShopId == shopID);
                            tb_order.OrderTime = orderTime;
                            tb_order.FetchTime = preCompleteTime;              //取件时间
                            tb_order.Status = (int)COM.OrderBagStatus.WaitPhotoMove;
                            tb_order.Remark = orderRemark;
                            users user = db.users.FirstOrDefault(u => u.userID == userId);
                            tb_order.users = user;

                            //照片路径: 总路径/商户/日期/订单包ID_包名/客户/产品名称
                            //string daoBaoMing = SaveTotalPath + "\\" + shopName + "\\" + DateTime.Now.Date.ToString("yyyy-MM-dd") + "\\" + OrderID.ToString() + "_" + orderName;    //路径到订单包
                            string daoBaoMing = SaveTotalPath + "\\" + shopName + "\\" + DateTime.Now.Date.ToString("yyyy-MM-dd") + "\\" + OrderID.ToString();    //路径到订单包
                            //2 保存产品

                            foreach (OrderInfo product in orderInfolist)
                            {
                                int xuhao = 1;  //订单包内照片的序号
           
                                string productPath = daoBaoMing + "\\" +product.CtmName+"\\"+ product.OrderProductName;//产品路径
                                //创建产品目录与备份目录
                                string productBackupPath = productPath + "\\" + "Backup";
                                if (!Directory.Exists(productBackupPath))
                                {
                                    try
                                    {
                                        Directory.CreateDirectory(productBackupPath);
                                        productPaths.Add(productPath);                  //产品路径
                                        productPaths.Add(productBackupPath);            //备份路径
                                    }
                                    catch
                                    {
                                        throw new Exception("无法连接指定的开单目录，请检查网络是否连通并且开单目录设置正确！");
                                    }
                                }
                                orderInfo newProduct = new orderInfo();
                                if (product.OrilOrderPath != string.Empty)
                                {
                                    DirectoryInfo oldOrderPath = new DirectoryInfo(product.OrilOrderPath);
                                    int indexCtm = product.OrilOrderPath.IndexOf(product.CtmName);
                                    string TemOrderPath = oldOrderPath.Root + "wh_order\\" + product.OrilOrderPath.Substring(indexCtm);
                                    newProduct.OrilOrderPath = TemOrderPath;        //订单内照片的原始目录(即临时文件夹下路径)
                                }
                                else//无照片产品
                                {
                                    newProduct.OrilOrderPath = string.Empty;
                                }

 
                                addProductInfo.Add(newProduct);
                                newProduct.CompleteTime = DateTime.Now;
                                newProduct.CtmName = product.CtmName;
                                newProduct.Height = product.Height;
                                newProduct.IsEdit = false;
                                newProduct.OrderPath = productPath;
                                newProduct.OrderProductCode = "2222222222";
                                newProduct.OrderProductName = product.OrderProductName;
                                

                                newProduct.Priority = orderPriority;
                                newProduct.productNum = product.ProductNum;
                                newProduct.OrilNum = product.ProductNum;
                                newProduct.SinglePageNum = 0;
                                newProduct.MultiPageNum = 0;
                                newProduct.OrderType = (int)OrderInfoType.Normal;//外部返单产品
                                newProduct.ProductType = product.ProductTypeCode;
                                newProduct.ComputerName = product.ComputerName;//开单电脑名称

                                if (!string.IsNullOrEmpty(product.CommonChargeItemNames))
                                {
                                    string[] itemsArr = product.CommonChargeItemNames.Split(',');
                                    newProduct.CommonChargeItem = new System.Data.Objects.DataClasses.EntityCollection<CommonChargeItem>();
                                    foreach (string itemName in itemsArr)
                                    {
                                        CommonChargeItem item = db.CommonChargeItem.FirstOrDefault(p => p.ItemName == itemName.Trim());
                                        if (item != null)
                                        {
                                            newProduct.CommonChargeItem.Add(item);
                                        }
                                    }
                                }

                                if (newProduct.Priority >= 7)
                                    newProduct.Remark = product.Remark + "\\急件";
                                else
                                    newProduct.Remark = product.Remark;

                                newProduct.status = (int)COM.OrderInfoStatus.WaitCheck;

                                newProduct.Tb_OrderBag = tb_order;
                                newProduct.Tb_Product = db.Tb_Product.First(p => p.ProuctId == product.ProductId);
                                newProduct.Width = product.Width;

                                //3 保存照片
                                //产品开单后的临时路径
                                double photoAreas = 0;//产品中照片的总面积
                                foreach (PhotoInfo photo in product.Photos)
                                {
                                    if (((BackgroundWorker)sender).CancellationPending)
                                    {
                                        throw new Exception("开单已取消！");
                                    }
                                    if (photo.isPictrue)
                                    {
                                        //photoAreas = 0;
                                        photoInfo newPhoto = new photoInfo();
                                        addPhotoInfo.Add(newPhoto);
                                        string realHW = photo.PhotoWH;
                                        int index = 0;

                                        newPhoto.orderInfo = newProduct;

                                        newPhoto.paperFace = db.paperFace.First(p => p.Name == photo.PaperFaceName);
                                        newPhoto.paperType = db.paperType.First(p => p.Name == photo.PaperTypeName);
                                        newPhoto.PhotoBarCode = "3333333333";
                                        string sx = xuhao.ToString(); //照片在订单包中的顺序

                                        newPhoto.photoName = photo.PhotoName; //照片名字
                                        //newPhoto.picPath = productPath + "\\" + sx + "_" + photo.PhotoName; //照片路径
                                        string productName =product.OrderPath.Substring(product.OrderPath.LastIndexOf("\\")+1);
                                        string fileName = Path.GetFileName(photo.PicPath);
                                        if (!fileName.Contains(productName))
                                        {
                                            newPhoto.picPath = productPath + "\\" + photo.PicPath.Substring(photo.PicPath.IndexOf(productName) + productName.Length + 1); //照片路径
                                        }
                                        else
                                        {
                                            newPhoto.picPath = Path.Combine(productPath, fileName);
                                        }
                                        newPhoto.pixHeight = photo.PixHeight;
                                        newPhoto.pixWidth = photo.PixWidth;

                                        newPhoto.printerId = 0; //打印机?
                                        newPhoto.Remark = photo.Remark == null ? "" : photo.Remark;
                                        newPhoto.Height = photo.Height;
                                        newPhoto.Width = photo.Width;
                                        newPhoto.TotalNum = photo.PhotoNum;
                                        photoAreas += Convert.ToDouble((photo.Height * 2.54) * (photo.Width * 2.54) / 10000 * newPhoto.TotalNum); //累计订单中照片的总面积计算一底多张
                                        newPhoto.status = (int)COM.PhotoStatus.WaitPhotoMove; //照片还未移动
                                        newPhoto.IsModifySize = photo.IsModifySize;

                                        newPhoto.OldPicPath = photo.PicPath;

                                        #region 默认打印机
                                        printer priter = db.printer.FirstOrDefault(p => p.PName == product.DefaultPrinterName);
                                        if (priter != null)
                                        {
                                            newPhoto.printerId = priter.PrinterID;             //默认打印机
                                        }
                                        else
                                        {
                                            newPhoto.printerId = 0;
                                        }
                                        db.SaveChanges();
                                        photo.PhotoId = Convert.ToInt32(newPhoto.EntityKey.EntityKeyValues[0].Value);
                                        #endregion

                                        xuhao++;
                                    }
                                    else//设定非照片文件临时目的路径
                                    {
                                        string allPath = photo.OldPicPath;
                                        int index4 = allPath.IndexOf(product.CtmName);

                                        DirectoryInfo oldpath = new DirectoryInfo(photo.OldPicPath);
                                        photo.PicPath = oldpath.Root.ToString() + "wh_order\\" + allPath.Substring(index4);
 
                                    }

                                }

                                //orderAreas += newProduct.Area;//统计订单的总面积 写入业绩
                                //4 WorkFlowList
                                List<WorkOrderFlowListInfo> workTechs = product.workFlows.OrderBy(w => w.WorkOrder).ToList();//按WorkOrder排序
                                int j = 0;
                                DateTime lastTechTime = orderTime;                //上个节点的完成时间(已开单时间初始化)
                                foreach (WorkOrderFlowListInfo tech in workTechs)
                                {
                                    if (tech.IsUsefull == false)                           //当前产品不需要该结点
                                        continue;
                                    WorkOrderFlowList work = new WorkOrderFlowList();
                                    work.tb_Tech = db.tb_Tech.First(t => t.TechId == tech.TechId);

                                    #region 商户节点指定操作员
                                    if (tech.UserName != string.Empty)
                                    {
                                        users dbuser = db.users.First(u => u.UserName == tech.UserName);
                                        tech.UserId = dbuser.userID;
                                    }
                                    else
                                    {
                                        tech.UserId = 0;
                                    }
                                    #endregion

                                    double techNeedTime = Convert.ToDouble(work.tb_Tech.NeedTime);
                                    work.IsEdit = false;
                                    if (j == 0)
                                    {
                                        work.Status = (int)COM.OrderFlowListStatus.Complete;
                                        work.UserId = userId;
                                        //统计开单员业绩
                                        startOrderFlows.Add(work);      //因为流程还未插入数据库，此时执行统计功能会出错，保存开单流程，插入数据后再统计
                                    }
                                    else if (j == 1)
                                    {
                                        work.Status = (int)COM.OrderFlowListStatus.Useable;
                                        work.UserId = tech.UserId;                      //默认操作员
                                    }
                                    else
                                    {
                                        work.Status = (int)COM.OrderFlowListStatus.Wait;
                                        work.UserId = tech.UserId;                      //默认操作员
                                    }
                                    work.AssignTime = lastTechTime;
                                    work.ReceiveTime = lastTechTime;
                                    work.PreCompleteTime = Convert.ToDateTime(work.ReceiveTime).AddHours(techNeedTime);
                                    work.CompletedTime = work.PreCompleteTime;
                                    lastTechTime = Convert.ToDateTime(work.CompletedTime);
                                    work.WorkOrder = tech.WorkOrder;
                                    if (tech.Techtype == (int)TechType.OutProduct && product.DefaultOutShopName != string.Empty)    //设置了默认委外商
                                    {
                                        OutProcessRecord opr = new OutProcessRecord();
                                        opr.orderInfo = newProduct;
                                        opr.OutProcessShop = db.OutProcessShop.First(o => o.OutShopName == product.DefaultOutShopName);
                                        opr.CreateTime = Convert.ToDateTime(work.AssignTime);
                                        opr.OutRemark = "";
                                        opr.PreFetchTime = lastTechTime;
                                        opr.FetchTime = lastTechTime;
                                        opr.FetchRemark = "";
                                        opr.users = db.users.First(u => u.userID == userId);
                                        opr.users1 = db.users.First(u => u.userID == userId);
                                        opr.Status = (int)COM.OutProcessRecordStatus.OutWaitFenDui;
                                        opr.Status2 = (int)COM.OutProcessRecordStatus2.Wait;
                                        opr.OperateUser = userId;
                                    }
                                    newProduct.WorkOrderFlowList.Add(work);
                                    j++;

                                }

                                //写入开单面积
                                WorkOrderFlowListInfo Designtech = workTechs.FirstOrDefault(p => p.IsDesign && p.IsUsefull);
                                int intPageNum = 0;//照片张数
                                newProduct.PageNum = product.PageNum;
                                photoAreas = photoAreas * product.ProductNum;//总面积
                                if (product.PageNum == -1)//单张片做产品比如水晶框之类
                                {
                                    intPageNum = product.Photos.Count * product.ProductNum;
                                }
                                else
                                {
                                    if (Designtech != null)
                                    {
                                        intPageNum = product.PageNum;
                                    }
                                    else
                                    {
                                        intPageNum = product.Photos.Count * product.ProductNum;
                                    }
                                }
                                if (Designtech != null)
                                {
                                    newProduct.Area = Convert.ToDouble((product.Width * 2.54) * (product.Height * 2.54) / 10000 * intPageNum * product.ProductNum);//按照设计好产品的尺寸计算

                                    switch (newProduct.ProductType)
                                    {
                                        case (int)OrderInfoProductType.NoNeedDesignPrint:
                                            newProduct.ProductType = (int)OrderInfoProductType.NeedDesignPrint;
                                            break;
                                        case (int)OrderInfoProductType.NoNeedDesignProduct:
                                            newProduct.ProductType = (int)OrderInfoProductType.NeedDesignProduct;
                                            
                                            break;
                                        case (int)OrderInfoProductType.NoNeedDesignKuoYin:
                                            newProduct.ProductType = (int)OrderInfoProductType.NeedDesignKuoYin;
                                            break;
                                        default:
                                            break;
                                    }
                                    //这里要把产品p数更新成模版的P数
                                    newProduct.PageNum = intPageNum;

                                }
                                else
                                {
                                    newProduct.Area = photoAreas;//不需要设计的按照照片的实际尺寸出

                                    switch (newProduct.ProductType)
                                    {
                                        case (int)OrderInfoProductType.NeedDesignPrint:
                                            newProduct.ProductType = (int)OrderInfoProductType.NoNeedDesignPrint;
                                            break;
                                        case (int)OrderInfoProductType.NeedDesignProduct:
                                            newProduct.ProductType = (int)OrderInfoProductType.NoNeedDesignProduct;
                                            break;
                                        case (int)OrderInfoProductType.NeedDesignKuoYin:
                                            newProduct.ProductType = (int)OrderInfoProductType.NoNeedDesignKuoYin;
                                            break;
                                        default:
                                            break;
                                    }
                                    if (newProduct.ProductType == (int)OrderInfoProductType.NoNeedDesignKuoYin)//修正扩印产品的开单面积
                                    {
                                        newProduct.Area = Convert.ToDouble((product.Width * 2.54) * (product.Height * 2.54) / 10000 * intPageNum);
                                    }

                                }


                            }
                            db.SaveChanges();

                            //更新
                            foreach (orderInfo item in addProductInfo)
                            {
                                item.OrderProductCode = "2" + string.Format("{0:d9}", Convert.ToInt32(item.EntityKey.EntityKeyValues[0].Value));
                            }
                            foreach (photoInfo item in addPhotoInfo)
                            {
                                item.PhotoBarCode = "3" + string.Format("{0:d9}", Convert.ToInt32(item.EntityKey.EntityKeyValues[0].Value));
                            }
                            db.SaveChanges();
                            //统计开单员业绩
                            double tempArea = 0;
                            foreach (WorkOrderFlowList flow in startOrderFlows)
                            {
                                workFlowListBll.NewStatWorkerPerformance(flow, db);
                            }
                            db.SaveChanges();

                             //开单完成后进行相关的统计工作
                            StataOrderBagInfo(OrderID, db);

                            //再对财务进行相关的审批工作
                            BillBLL.UpdateBillInfo(tb_order.OrderBagId,db);
                            tran.Commit();//开单成功，提交事务
                        }
                        catch (Exception ex)
                        {
                            tran.Rollback();
                            throw ex;
                        }

                    }
                }

            }
            catch (Exception ex)
            {
                
                throw ex;
            }
        }


        #region 旧开单保存订单记录
        /// <summary>
        /// 开单
        /// </summary>
        public void OldAddOrderBag(object sender, DoWorkEventArgs e, List<OrderInfo> orderInfolist, int OrderID, string OrderBagCode, string orderName, int orderPriority, int shopID, string shopName, DateTime orderTime, DateTime preCompleteTime, string orderRemark, int userId)
        {
            List<WorkOrderFlowList> startOrderFlows = new List<WorkOrderFlowList>();       //开单流程，插入开单信息后统计开单员业绩
            //List<string> PhotoTemps = new List<string>();       //开单断网后照片复位
            //List<string> MovedTarPaths = new List<string>();    //上次断网时已移动了的照片路径
            List<orderInfo> addProductInfo = new List<orderInfo>();     //新插入的产品集合
            List<photoInfo> addPhotoInfo = new List<photoInfo>();       //新插入的照片集合 
            DateTime realOrderTime = _dal.GetServerTime();                //真实开单时间取服务器的时间
            preCompleteTime = realOrderTime.Add(preCompleteTime - orderTime);   //真实预计完成时间=真实开单时间+(本地预计完成时间-本地开单时间)
            orderTime = realOrderTime;
            System.Transactions.TransactionOptions options = new TransactionOptions();
            options.Timeout = new TimeSpan(0, 0, 600);
            options.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;
            Tb_OrderBag tb_order = null;
            int connectTime = 0;
            //double orderAreas = 0;
            try
            {
                using (newSampleYPDBEntities db = new newSampleYPDBEntities())
                {
                    using (TransactionScope tran = new TransactionScope(TransactionScopeOption.Required, options))
                    {
                        Shop shop = db.Shop.First(s => s.ShopId == shopID);
                        shop.LastPrintDate = DateTime.Now;
                        db.SaveChanges();
                        List<string> productPaths = new List<string>();             //保存产品的路径,出错后删除复制的产品信息

                        string SaveTotalPath = db.FileDirPath.First(f => f.Des == "已开单").FileDir;                 //照片在服务器上的总路径

                        //string DelPath = SaveTotalPath + "\\" + shopName + "\\" + DateTime.Now.Date.ToString("yyyy-MM-dd") + "\\" + OrderID.ToString() + "_" + orderName;    //如果出错删除该目录
                        string DelPath = SaveTotalPath + "\\" + shopName + "\\" + DateTime.Now.Date.ToString("yyyy-MM-dd") + "\\" + OrderID.ToString();    //如果出错删除该目录
                        try
                        {
                            //1 保存订单包

                            tb_order = db.Tb_OrderBag.Where("it.OrderBagId=" + OrderID).FirstOrDefault();
                            if (tb_order == null)
                            {
                                throw new Exception("同一帐号在别处正打开，请退出其它处登陆，重新打开开单界面，再进行开单！");
                            }
                            tb_order.BagCode = OrderBagCode;
                            tb_order.BagName = orderName;
                            tb_order.Priority = orderPriority;
                            tb_order.Shop = db.Shop.First(s => s.ShopId == shopID);
                            tb_order.OrderTime = orderTime;
                            tb_order.FetchTime = preCompleteTime;              //取件时间
                            tb_order.Status = (int)COM.OrderBagStatus.WaitPhotoMove;
                            tb_order.Remark = orderRemark;
                            users user = db.users.FirstOrDefault(u => u.userID == userId);
                            tb_order.users = user;

                            //照片路径: 总路径/商户/日期/订单包ID_包名/客户/产品名称
                            //string daoBaoMing = SaveTotalPath + "\\" + shopName + "\\" + DateTime.Now.Date.ToString("yyyy-MM-dd") + "\\" + OrderID.ToString() + "_" + orderName;    //路径到订单包
                            string daoBaoMing = SaveTotalPath + "\\" + shopName + "\\" + DateTime.Now.Date.ToString("yyyy-MM-dd") + "\\" + OrderID.ToString();    //路径到订单包
                            //2 保存产品

                            foreach (OrderInfo product in orderInfolist)
                            {
                                int xuhao = 1;  //订单包内照片的序号

                                string productPath = daoBaoMing + "\\" + product.CtmName + "\\" + product.OrderProductName;//产品路径
                                //创建产品目录与备份目录
                                string productBackupPath = productPath + "\\" + "Backup";
                                if (!Directory.Exists(productBackupPath))
                                {
                                    try
                                    {
                                        Directory.CreateDirectory(productBackupPath);
                                        productPaths.Add(productPath);                  //产品路径
                                        productPaths.Add(productBackupPath);            //备份路径
                                    }
                                    catch
                                    {
                                        throw new Exception("无法连接指定的开单目录，请检查网络是否连通并且开单目录设置正确！");
                                    }
                                }
                                orderInfo newProduct = new orderInfo();
                                if (product.OrilOrderPath != string.Empty)
                                {
                                    DirectoryInfo oldOrderPath = new DirectoryInfo(product.OrilOrderPath);
                                    int indexCtm = product.OrilOrderPath.IndexOf(product.CtmName);
                                    string TemOrderPath = oldOrderPath.Root + "wh_order\\" + product.OrilOrderPath.Substring(indexCtm);
                                    newProduct.OrilOrderPath = TemOrderPath;        //订单内照片的原始目录(即临时文件夹下路径)
                                }
                                else//无照片产品
                                {
                                    newProduct.OrilOrderPath = string.Empty;
                                }


                                addProductInfo.Add(newProduct);
                                newProduct.CompleteTime = DateTime.Now;
                                newProduct.CtmName = product.CtmName;
                                newProduct.Height = product.Height;
                                newProduct.IsEdit = false;
                                newProduct.OrderPath = productPath;
                                newProduct.OrderProductCode = "2222222222";
                                newProduct.OrderProductName = product.OrderProductName;


                                newProduct.Priority = orderPriority;
                                newProduct.productNum = product.ProductNum;
                                newProduct.OrilNum = product.ProductNum;
                                newProduct.SinglePageNum = 0;
                                newProduct.MultiPageNum = 0;
                                newProduct.OrderType = (int)OrderInfoType.Normal;//外部返单产品
                                newProduct.ProductType = product.ProductTypeCode;
                                newProduct.ComputerName = product.ComputerName;//开单电脑名称

                                if (!string.IsNullOrEmpty(product.CommonChargeItemNames))
                                {
                                    string[] itemsArr = product.CommonChargeItemNames.Split(',');
                                    newProduct.CommonChargeItem = new System.Data.Objects.DataClasses.EntityCollection<CommonChargeItem>();
                                    foreach (string itemName in itemsArr)
                                    {
                                        CommonChargeItem item = db.CommonChargeItem.FirstOrDefault(p => p.ItemName == itemName.Trim());
                                        if (item != null)
                                        {
                                            newProduct.CommonChargeItem.Add(item);
                                        }
                                    }
                                }

                                if (newProduct.Priority >= 7)
                                    newProduct.Remark = product.Remark + "\\急件";
                                else
                                    newProduct.Remark = product.Remark;

                                newProduct.status = (int)COM.OrderInfoStatus.WaitCheck;

                                newProduct.Tb_OrderBag = tb_order;
                                newProduct.Tb_Product = db.Tb_Product.First(p => p.ProuctId == product.ProductId);
                                newProduct.Width = product.Width;

                                //3 保存照片
                                //产品开单后的临时路径
                                double photoAreas = 0;//产品中照片的总面积
                                foreach (PhotoInfo photo in product.Photos)
                                {
                                    if (((BackgroundWorker)sender).CancellationPending)
                                    {
                                        throw new Exception("开单已取消！");
                                    }
                                    if (photo.isPictrue)
                                    {
                                        //photoAreas = 0;
                                        photoInfo newPhoto = new photoInfo();
                                        addPhotoInfo.Add(newPhoto);
                                        string realHW = photo.PhotoWH;
                                        int index = 0;

                                        newPhoto.orderInfo = newProduct;

                                        newPhoto.paperFace = db.paperFace.First(p => p.Name == photo.PaperFaceName);
                                        newPhoto.paperType = db.paperType.First(p => p.Name == photo.PaperTypeName);
                                        newPhoto.PhotoBarCode = "3333333333";
                                        string sx = xuhao.ToString(); //照片在订单包中的顺序

                                        newPhoto.photoName = photo.PhotoName; //照片名字
                                        //newPhoto.picPath = productPath + "\\" + sx + "_" + photo.PhotoName; //照片路径
                                        string productName = product.OrderPath.Substring(product.OrderPath.LastIndexOf("\\") + 1);
                                        newPhoto.picPath = productPath + "\\" + photo.PicPath.Substring(photo.PicPath.IndexOf(productName) + productName.Length + 1); //照片路径
                                        newPhoto.pixHeight = photo.PixHeight;
                                        newPhoto.pixWidth = photo.PixWidth;

                                        newPhoto.printerId = 0; //打印机?
                                        newPhoto.Remark = photo.Remark == null ? "" : photo.Remark;
                                        newPhoto.Height = photo.Height;
                                        newPhoto.Width = photo.Width;
                                        newPhoto.TotalNum = photo.PhotoNum;
                                        photoAreas += Convert.ToDouble((photo.Height * 2.54) * (photo.Width * 2.54) / 10000 * newPhoto.TotalNum); //累计订单中照片的总面积计算一底多张
                                        newPhoto.status = (int)COM.PhotoStatus.WaitPhotoMove; //照片还未移动
                                        newPhoto.IsModifySize = photo.IsModifySize;

                                        newPhoto.OldPicPath = photo.PicPath;

                                        #region 默认打印机
                                        printer priter = db.printer.FirstOrDefault(p => p.PName == product.DefaultPrinterName);
                                        if (priter != null)
                                        {
                                            newPhoto.printerId = priter.PrinterID;             //默认打印机
                                        }
                                        else
                                        {
                                            newPhoto.printerId = 0;
                                        }
                                        db.SaveChanges();
                                        photo.PhotoId = Convert.ToInt32(newPhoto.EntityKey.EntityKeyValues[0].Value);
                                        #endregion

                                        xuhao++;
                                    }
                                    else//设定非照片文件临时目的路径
                                    {
                                        string allPath = photo.OldPicPath;
                                        int index4 = allPath.IndexOf(product.CtmName);

                                        DirectoryInfo oldpath = new DirectoryInfo(photo.OldPicPath);
                                        photo.PicPath = oldpath.Root.ToString() + "wh_order\\" + allPath.Substring(index4);

                                    }

                                }

                                //orderAreas += newProduct.Area;//统计订单的总面积 写入业绩
                                //4 WorkFlowList
                                List<WorkOrderFlowListInfo> workTechs = product.workFlows.OrderBy(w => w.WorkOrder).ToList();//按WorkOrder排序
                                int j = 0;
                                DateTime lastTechTime = orderTime;                //上个节点的完成时间(已开单时间初始化)
                                foreach (WorkOrderFlowListInfo tech in workTechs)
                                {
                                    if (tech.IsUsefull == false)                           //当前产品不需要该结点
                                        continue;
                                    WorkOrderFlowList work = new WorkOrderFlowList();
                                    work.tb_Tech = db.tb_Tech.First(t => t.TechId == tech.TechId);

                                    #region 商户节点指定操作员
                                    if (tech.UserName != string.Empty)
                                    {
                                        users dbuser = db.users.First(u => u.UserName == tech.UserName);
                                        tech.UserId = dbuser.userID;
                                    }
                                    else
                                    {
                                        tech.UserId = 0;
                                    }
                                    #endregion

                                    double techNeedTime = Convert.ToDouble(work.tb_Tech.NeedTime);
                                    work.IsEdit = false;
                                    if (j == 0)
                                    {
                                        work.Status = (int)COM.OrderFlowListStatus.Complete;
                                        work.UserId = userId;
                                        //统计开单员业绩
                                        startOrderFlows.Add(work);      //因为流程还未插入数据库，此时执行统计功能会出错，保存开单流程，插入数据后再统计
                                    }
                                    else if (j == 1)
                                    {
                                        work.Status = (int)COM.OrderFlowListStatus.Useable;
                                        work.UserId = tech.UserId;                      //默认操作员
                                    }
                                    else
                                    {
                                        work.Status = (int)COM.OrderFlowListStatus.Wait;
                                        work.UserId = tech.UserId;                      //默认操作员
                                    }
                                    work.AssignTime = lastTechTime;
                                    work.ReceiveTime = lastTechTime;
                                    work.PreCompleteTime = Convert.ToDateTime(work.ReceiveTime).AddHours(techNeedTime);
                                    work.CompletedTime = work.PreCompleteTime;
                                    lastTechTime = Convert.ToDateTime(work.CompletedTime);
                                    work.WorkOrder = tech.WorkOrder;
                                    if (tech.Techtype == (int)TechType.OutProduct && product.DefaultOutShopName != string.Empty)    //设置了默认委外商
                                    {
                                        OutProcessRecord opr = new OutProcessRecord();
                                        opr.orderInfo = newProduct;
                                        opr.OutProcessShop = db.OutProcessShop.First(o => o.OutShopName == product.DefaultOutShopName);
                                        opr.CreateTime = Convert.ToDateTime(work.AssignTime);
                                        opr.OutRemark = "";
                                        opr.PreFetchTime = lastTechTime;
                                        opr.FetchTime = lastTechTime;
                                        opr.FetchRemark = "";
                                        opr.users = db.users.First(u => u.userID == userId);
                                        opr.users1 = db.users.First(u => u.userID == userId);
                                        opr.Status = (int)COM.OutProcessRecordStatus.OutWaitFenDui;
                                        opr.Status2 = (int)COM.OutProcessRecordStatus2.Wait;
                                        opr.OperateUser = userId;
                                    }
                                    newProduct.WorkOrderFlowList.Add(work);
                                    j++;

                                }

                                //写入开单面积
                                WorkOrderFlowListInfo Designtech = workTechs.FirstOrDefault(p => p.IsDesign && p.IsUsefull);
                                int intPageNum = 0;//照片张数
                                newProduct.PageNum = product.PageNum;
                                photoAreas = photoAreas * product.ProductNum;//总面积
                                if (product.PageNum == -1)//单张片做产品比如水晶框之类
                                {
                                    intPageNum = product.Photos.Count * product.ProductNum;
                                }
                                else
                                {
                                    intPageNum = product.Photos.Count * product.ProductNum;
                                }
                                if (Designtech != null)
                                {
                                    newProduct.Area = Convert.ToDouble((product.Width * 2.54) * (product.Height * 2.54) / 10000 * product.PageNum * product.ProductNum);//按照设计好产品的尺寸计算

                                    switch (newProduct.ProductType)
                                    {
                                        case (int)OrderInfoProductType.NoNeedDesignPrint:
                                            newProduct.ProductType = (int)OrderInfoProductType.NeedDesignPrint;
                                            break;
                                        case (int)OrderInfoProductType.NoNeedDesignProduct:
                                            newProduct.ProductType = (int)OrderInfoProductType.NeedDesignProduct;
                                            break;
                                        case (int)OrderInfoProductType.NoNeedDesignKuoYin:
                                            newProduct.ProductType = (int)OrderInfoProductType.NeedDesignKuoYin;
                                            break;
                                        default:
                                            break;
                                    }
                                }
                                else
                                {
                                    newProduct.Area = photoAreas;//不需要设计的按照照片的实际尺寸出

                                    switch (newProduct.ProductType)
                                    {
                                        case (int)OrderInfoProductType.NeedDesignPrint:
                                            newProduct.ProductType = (int)OrderInfoProductType.NoNeedDesignPrint;
                                            break;
                                        case (int)OrderInfoProductType.NeedDesignProduct:
                                            newProduct.ProductType = (int)OrderInfoProductType.NoNeedDesignProduct;
                                            break;
                                        case (int)OrderInfoProductType.NeedDesignKuoYin:
                                            newProduct.ProductType = (int)OrderInfoProductType.NoNeedDesignKuoYin;
                                            break;
                                        default:
                                            break;
                                    }
                                    if (newProduct.ProductType == (int)OrderInfoProductType.NoNeedDesignKuoYin)//修正扩印产品的开单面积
                                    {
                                        newProduct.Area = Convert.ToDouble((product.Width * 2.54) * (product.Height * 2.54) / 10000 * intPageNum);
                                    }

                                }


                            }
                            db.SaveChanges();

                            //更新
                            foreach (orderInfo item in addProductInfo)
                            {
                                item.OrderProductCode = "2" + string.Format("{0:d9}", Convert.ToInt32(item.EntityKey.EntityKeyValues[0].Value));
                            }
                            foreach (photoInfo item in addPhotoInfo)
                            {
                                item.PhotoBarCode = "3" + string.Format("{0:d9}", Convert.ToInt32(item.EntityKey.EntityKeyValues[0].Value));
                            }
                            db.SaveChanges();
                            //统计开单员业绩
                            double tempArea = 0;
                            foreach (WorkOrderFlowList flow in startOrderFlows)
                            {
                                workFlowListBll.NewStatWorkerPerformance(flow, db);
                            }
                            db.SaveChanges();

                            //开单完成后进行相关的统计工作
                            StataOrderBagInfo(OrderID, db);

                            //再对财务进行相关的审批工作
                            BillBLL.UpdateBillInfo(tb_order.OrderBagId, db);
                            tran.Complete();//开单成功，提交事务
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }

                    }
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion
        /// <summary>
        /// 开单完成后进行相关的统计工作
        /// </summary>
        /// <param name="orderBagId"></param>
        /// <returns></returns>
        public int StataOrderBagInfo(int orderBagId,newSampleYPDBEntities dataBase)
        {
            int result = 1;
 
                Tb_OrderBag tbOrderBag = dataBase.Tb_OrderBag.FirstOrDefault(ob => ob.OrderBagId == orderBagId);
                if (tbOrderBag != null)
                {
                    if (!tbOrderBag.orderInfo.IsLoaded)
                    {
                        tbOrderBag.orderInfo.Load();
                    }

                    foreach (var oi in tbOrderBag.orderInfo.ToList())
                    {
                        //double OiArea = GetAreaByOi(oi, dataBase);
                        SataShopProductAndOrderArea(oi, dataBase, oi.Area);
                        try
                        {
                            dataBase.SaveChanges();
                            //WriteLogForCheck.WriteLogFile("统计完成面积为：" + OiArea.ToString());
                        }
                        catch (Exception ex)//记录日志
                        {
                            //WriteLogForCheck.WriteLogFile("在进行产品和每日开单面积统计时出错：" + ex.Message);
                            result = 0;
                            break;
                        }

                    }
                }
            
            return result;
        }

        /// <summary>
        /// 统计商户的开单产品和开单面积
        /// </summary>
        /// <param name="oi"></param>
        /// <param name="dataBase"></param>
        /// <param name="PhotoAreas"></param>
        private void SataShopProductAndOrderArea(orderInfo oi, newSampleYPDBEntities dataBase, double PhotoAreas)
        {
            if (!oi.Tb_ProductReference.IsLoaded)
                oi.Tb_ProductReference.Load();

            if (!oi.Tb_OrderBagReference.IsLoaded)
                oi.Tb_OrderBagReference.Load();

            if (!oi.Tb_OrderBag.ShopReference.IsLoaded)
                oi.Tb_OrderBag.ShopReference.Load();

            #region 商户下单产品统计

            string strSpc = oi.Tb_Product.Width + "*" + oi.Tb_Product.Height;
            ShopProduct sp = dataBase.ShopProduct.FirstOrDefault(p => p.ShopName == oi.Tb_OrderBag.Shop.shopName && p.ProductName == oi.Tb_Product.ProductName && p.Spec == strSpc && p.OrderTime == oi.Tb_OrderBag.OrderTime.Date);

            if (sp == null)//添加新的
            {
                ShopProduct spNew = new ShopProduct()
                {
                    Area = PhotoAreas,
                    OrderTime = oi.Tb_OrderBag.OrderTime.Date,
                    ProductName = oi.Tb_Product.ProductName,
                    ProductNum = 1,
                    ShopName = oi.Tb_OrderBag.Shop.shopName,
                    Spec = oi.Tb_Product.Width + "*" + oi.Tb_Product.Height
                };
                dataBase.AddToShopProduct(spNew);
            }
            else
            {
                sp.Area += PhotoAreas;
                sp.ProductNum++;
            }

            #endregion

            #region 每日开单面积统计

            CreateOrderAreaByDay orderArea = dataBase.CreateOrderAreaByDay.FirstOrDefault(d => d.CreateOrderDate == oi.Tb_OrderBag.OrderTime.Date && d.AreaName == oi.Tb_OrderBag.Shop.Area && d.ShopName == oi.Tb_OrderBag.Shop.shopName);
            if (orderArea == null)
            {
                CreateOrderAreaByDay newDay = new CreateOrderAreaByDay()
                {
                    CreateOrderDate = oi.Tb_OrderBag.OrderTime.Date,
                    Area = PhotoAreas,
                    ShopName = oi.Tb_OrderBag.Shop.shopName,
                    AreaName = oi.Tb_OrderBag.Shop.Area
                };
                dataBase.AddToCreateOrderAreaByDay(newDay);
            }
            else
            {
                orderArea.Area += PhotoAreas;
            }
            #endregion

        }





        /// <summary>
        /// 获得等待移动的产品列表
        /// </summary>
        /// <param name="comPuterName">开单电脑名称</param>
        /// <returns>等待移动的产品列表</returns>
        public List<MoveOrderInfo> GetMoveOrderInfoList(string comPuterName)
        {
            List<MoveOrderInfo> list = new List<MoveOrderInfo>();
            try
            {
                using (newSampleYPDBEntities db = new newSampleYPDBEntities())
                {
                    List<orderInfo> orderInfolist = db.orderInfo.Where(o => o.ComputerName == comPuterName && o.status == (int)OrderInfoStatus.WaitPhotoMove || o.status == (int)OrderInfoStatus.WaitPayAndWaitMovePhoto).ToList();
                    foreach (var item in orderInfolist)
                    {
                        if(!item.Tb_OrderBagReference.IsLoaded)
                            item.Tb_OrderBagReference.Load();
                        if(!item.photoInfo.IsLoaded)
                            item.photoInfo.Load();
                        List<MovePhotoInfo> photoList = new List<MovePhotoInfo>();
                        foreach (var photo in item.photoInfo)
                        {
                            MovePhotoInfo photoInfo = new MovePhotoInfo()
                            {
                                PhotoId = photo.photoId,
                                MoveStatus = photo.status,
                                OldPicPath = photo.OldPicPath,
                                PicPath = photo.picPath,
                                ErrorMsg = string.Empty
                            };
                            photoList.Add(photoInfo);
                        }

                        MoveOrderInfo moveOrderInfo = new MoveOrderInfo()
                        {
                            OrderInfoId = item.OrderProductId,
                            OrderTime = item.Tb_OrderBag.OrderTime,
                            PhotoNum = "0/" + item.photoInfo.Count.ToString(),
                            ProcessPosition = 0,
                            Status = item.status,
                            photoList = photoList,
                            LocalPath = item.OrilOrderPath,
                            OrderPath = item.OrderPath
                        };
                        list.Add(moveOrderInfo);
                    }
                }
            }
            catch(Exception ex)
            {
                throw ex;
            }

            return list;
        }

        /// <summary>
        /// 删除临时站位订单包
        /// </summary>
        /// <param name="orderbagId"></param>
        public void DeleteTempOrderBag(int orderbagId)
        {
            try
            {
                using (newSampleYPDBEntities db = new newSampleYPDBEntities())
                {
                    Tb_OrderBag orderbag = db.Tb_OrderBag.FirstOrDefault(o => o.OrderBagId == orderbagId);
                    if (orderbag != null)
                    {
                        db.DeleteObject(orderbag);
                        db.SaveChanges();
                    }
                }
            }
            catch
            {
 
            }
        }

        #region 读取txt文件信息
        /// <summary>
        /// 读取txt文件信息
        /// </summary>
        /// <param name="productPath"></param>
        /// <returns></returns>
        private string GetRemarkOfProduct(string productPath)
        {
            StringBuilder productRemark = new StringBuilder();
            if (!Directory.Exists(productPath))
            {
                return "";
            }
            string CtmContext = GetCtmContext(productPath);
            GetTXTContext(productPath, productRemark);

            return CtmContext + productRemark.ToString();
        }

        private void GetTXTContext(string inStrPath, StringBuilder outContext)
        {
           
            string[] strDir = Directory.GetDirectories(inStrPath);
            DirectoryInfo faceInfo = new DirectoryInfo(inStrPath);
            FileInfo[] faceArrInfo = faceInfo.GetFiles("*.txt");
            //string strContext = "";
            foreach (FileInfo fileInfo in faceArrInfo)
            {
                StreamReader reader = new StreamReader(fileInfo.FullName, System.Text.Encoding.GetEncoding("gb2312"));
                outContext.Append(reader.ReadToEnd());
                outContext.Append(@"|");//文件分隔符
                reader.Close();
            }
            if (strDir.Length > 0)
            {
                foreach (string s in strDir)
                {
                    GetTXTContext(s, outContext);
                }
            }
            else
            {
                DirectoryInfo directoryInfo = new DirectoryInfo(inStrPath);
                FileInfo[] fileArrInfo = directoryInfo.GetFiles("*.txt");
                //string strContext = "";
                foreach (FileInfo fileInfo in fileArrInfo)
                {
                    StreamReader reader = new StreamReader(fileInfo.FullName, System.Text.Encoding.GetEncoding("gb2312"));
                    outContext.Append(reader.ReadToEnd());
                    outContext.Append(@"|");//文件分隔符
                    reader.Close();
                }

            }
        }
        private string GetCtmContext(string inProductPath)
        {
            DirectoryInfo directoryInfo = new DirectoryInfo(inProductPath);
            DirectoryInfo parentDir = directoryInfo.Parent;

            FileInfo[] fileArrInfo = parentDir.GetFiles("*.txt");
            string strContext = "";
            foreach (FileInfo fileInfo in fileArrInfo)
            {
                StreamReader reader = new StreamReader(fileInfo.FullName, System.Text.Encoding.GetEncoding("gb2312"));
                strContext += reader.ReadToEnd();
                strContext += @"|";//文件分隔符
                reader.Close();
            }
            return strContext;
        }
        #endregion


        /// <summary>
        /// 判断这个商户是否设置了这种纸型的价格
        /// </summary>
        /// <param name="shopId"></param>
        /// <param name="paperTypeId"></param>
        /// <returns></returns>
        public bool IsPaperTypeSetPrice(int shopId,int paperTypeId)
        {
            bool flag = false;
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                List<Shop_Paper_Price> sppList = db.Shop_Paper_Price.Where(s => s.ShopId == shopId).ToList();
                Shop_Paper_Price spp = sppList.FirstOrDefault(s => s.PaperTypeId == paperTypeId);
                if (spp != null)
                {
                    flag = true;
                }
                else
                {
                    flag = false;
                }
            }
            return flag;
        }

    }

}
